package com.example.demo.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: cj
 * @create: 14-01-10 14:52:24
 */
@Component
public class OssUtil {
    @Resource
    OSSClient ossClient;
    @Value("${alias.bucketName}")
    String bucketName;
    @Value("${alias.endpoint}")
    String endpoint;

    public Map<String, Object> uploadFile(MultipartFile file) throws IOException {
        // 获取文件后缀名
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        int i = originalFilename.lastIndexOf( "." );
        String png = originalFilename.substring( i + 1 );
        String fileName = png + "/" + new SimpleDateFormat( "yyyyMMddHHmm" ).format( new Date() ) + (new Random()).nextInt( 9 ) + "." + png;
        ossClient.putObject( bucketName, fileName, file.getInputStream() );
        //https://testdemo012.oss-cn-beijing.aliyuncs.com/jpg/2022011015378.jpg
        Map<String, Object> map = new HashMap<>( 5 );
        map.put( "path", "https://" + bucketName + "." + endpoint + "/" + fileName );
        map.put( "fileName", fileName );
        return map;
    }

    public void del(List<String> list) {
        DeleteObjectsRequest deleteObject = new DeleteObjectsRequest( bucketName );
        DeleteObjectsRequest deleteObjectsRequest = deleteObject.withKeys( list );
        ossClient.deleteObjects( deleteObjectsRequest );
    }


}
